package com.scse.bms.web.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scse.bms.domain.ThemeVO;
import com.scse.bms.entity.ThemeDO;
import com.scse.bms.service.ThemeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Title: ThemeController
 * @Author: 吴赠禹
 * @Date: 2021/2/20 0:17
 * @Version: 1.0
 * @Description: TODO
 */

@Slf4j
@Controller
public class ThemeController {


    @Autowired
    private ThemeService themeService;


    /**
     * 这是通过form提交的post方法
     * @param theme
     * @return
     */
    @PutMapping("theme/put")
    public String updateTheme(ThemeVO theme) {
        log.info("[updateTheme] 修改记录{}", theme);
        themeService.updateById(theme);
        return "redirect:/admin/theme";
    }


    /**
     * 通过表单提交
     * @param theme
     * @return
     */
    @PostMapping("/theme/add")
    public String addTheme(ThemeVO theme) {
        log.info("[addTheme] 添加一条记录{}", theme);
        themeService.save(theme);
        return "redirect:/admin/theme";

    }


    /**
     * 删除主题
     * @param id
     * @return
     */
    @PostMapping("/theme/delete/{id}")
    @ResponseBody
    public String deleteTheme(@PathVariable("id") Integer id) {
        log.info("[deleteTheme] 删除一条记录{}", id);
        // 判断该主题下是否有书，有则不予删除（不在后端判断，因为主题列表中已有数量，前端进行数量判断）
        // Integer num = themeService.getBookNumByThemeId(id);
        boolean result = themeService.removeById(id);
        return String.valueOf(result);
    }


    /**
     * 分页查询主题列表
     * @param pn
     * @param limit
     * @param model
     * @return
     */
    @GetMapping("/admin/themeList")
    public String getTheme(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
                           @RequestParam(required = false, defaultValue = "4") Integer limit, Model model) {
        log.info("[getTheme] 获取主题列表，分页：pn={}, limit={}", pn, limit);
        // 分页查询数据
        Page<ThemeVO> themePage = new Page<>(pn, limit);
        // 分页查询的结果
        IPage<ThemeVO> page = themeService.getThemeListByPage(themePage);
        model.addAttribute("themes", page);
        return "back/themeList";
    }


}
